"""
事件循环

获取返回值future
"""

import time
import asyncio
from functools import partial


async def get_html(url):
    print("start get url")
    # await的用法：await Awaitable
    await asyncio.sleep(2)
    print("end get url")
    return "Apple"


def callback(future):
    """
    回调
    """

    print("send email to Kevin")


def partial_callback(url, future):
    """
    回调
    参数需要放在future前面
    """

    print(url)
    print("send email to Kevin")


def use_asyncio():
    start_time = time.time()

    # 事件循环
    loop = asyncio.get_event_loop()

    # 使用future的形式
    future = asyncio.ensure_future(get_html("http://www.imooc.com"))
    # future.add_done_callback(callback)
    # 将函数包装成另一个函数
    future.add_done_callback(partial(partial_callback, "http://www.imooc.com"))
    loop.run_until_complete(future)
    print(future.result())

    # 使用task的形式（task是future的子类）
    # task = loop.create_task(get_html("http://www.imooc.com"))
    # task.add_done_callback(callback)
    # loop.run_until_complete(task)
    # print(task.result())

    print("耗时：", time.time() - start_time)
    # 输出结果：
    """
    start get url
    end get url
    http://www.imooc.com
    send email to Kevin
    Apple
    耗时： 2.014324903488159
    """


if __name__ == '__main__':
    use_asyncio()
